package com.caimiao.miao.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.caimiao.miao.bean.Response;
import com.caimiao.miao.bean.TicketOut;
import com.caimiao.miao.http.HttpUtil;
import com.caimiao.miao.http.rxjava.transformer.SchedulerTransformer;
import com.caimiao.miao.library.bluetooth.state.IBtState;
import com.caimiao.miao.library.database.DBHelperFactory;
import com.caimiao.miao.library.database.table.DeviceDBHelper;
import com.caimiao.miao.library.database.table.TicketOutDBHelper;
import com.caimiao.miao.library.utils.sys.DeviceUtil;
import com.caimiao.miao.library.utils.tip.PrintLog;
import com.caimiao.miao.page.ticket.TicketActivity;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;

public class MiaoService extends Service implements IBleContact.View {
    private static final String TAG = "MiaoService";
    private IBleContact.Presenter mBtPresenter;
    private static boolean isStart;
    private Disposable mDisposable;
    private String mDeviceId;

    public class LocalBinder extends Binder {
        public MiaoService getService() {
            return MiaoService.this;
        }
    }

    public static boolean isStart() {
        return isStart;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        isStart = true;
        new BlePresenter(this);
        mDeviceId = DeviceUtil.getDeviceId(this);
//        startTakeTicket();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new LocalBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        isStart = false;
        mBtPresenter.detach();
        if (mDisposable != null)
            mDisposable.dispose();
        mDisposable = null;
        super.onDestroy();
    }

    @Override
    public void setPresenter(IBleContact.Presenter presenter) {
        mBtPresenter = presenter;
        mBtPresenter.start(this);
    }

    /**************************************定时拉票************************************************/
    public void startTakeTicket() {
        mDisposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .flatMap(new Function<Long, ObservableSource<Response<TicketOut>>>() {
                    @Override
                    public ObservableSource<Response<TicketOut>> apply(Long aLong) throws Exception {
                        return HttpUtil.getTicketOut(mDeviceId);
                    }
                })
                .filter(new Predicate<Response<TicketOut>>() {
                    @Override
                    public boolean test(Response<TicketOut> response) throws Exception {
                        return response.getData() != null;
                    }
                })
                .map(new Function<Response<TicketOut>, Response<TicketOut>>() {
                    @Override
                    public Response<TicketOut> apply(Response<TicketOut> response) throws Exception {
                        boolean result = DBHelperFactory
                                .getDBHelper(TicketOutDBHelper.class)
                                .hasTrade(response.getData().getOut_trade_no());
                        Log.e(TAG, "调取接口，result = " + result);
                        if (result) response.setData(null);
                        return response;
                    }
                })
                .filter(new Predicate<Response<TicketOut>>() {
                    @Override
                    public boolean test(Response<TicketOut> response) throws Exception {
                        return response.getData() != null;
                    }
                })
                .compose(SchedulerTransformer.applyIoAndUi())
                .subscribe(new Consumer<Response<TicketOut>>() {
                    @Override
                    public void accept(Response<TicketOut> response) throws Exception {
                        Log.e(TAG, "调取接口，data = " + response.getData());
                        Intent intent = new Intent(getApplicationContext(), TicketActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra(TicketActivity.EXTRA_DATA, response.getData());
                        getApplicationContext().startActivity(intent);
                        stopTakeTicket();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    public void stopTakeTicket() {
        if (mDisposable != null)
            mDisposable.dispose();
    }

    public void restartTakeTicket() {
        stopTakeTicket();
        startTakeTicket();
    }

    /**************************************入票****************************************************/

    public void postAddTicket() {

    }

    /**************************************出票****************************************************/

    public Observable<IBtState> setOutTicket(int num) {
//        stopTakeTicket();
        PrintLog.printBle("开始出票，票数：" + num);
        return mBtPresenter.setOutTicket(num);
    }

    public void setReOutTicket() {
        mBtPresenter.setReOutTicket();
    }

    public void postTickOut() {
        mBtPresenter.postTickOut(this);
    }
}
